var pageNow = 1;
var pageSize = 5;
var totalCount = 0;
var pageCount = 0;

$(document).ready(search());

function search() {
	var bookName = $('#bookName').val();
	var btypeId = $('#btypeId').val();
	var params = '{"bookName" : "' + bookName + '", "btypeId" : "' + btypeId
			+ '", "pageNow" : "' + pageNow + '", "pageSize" : "' + pageSize
			+ '"}';
	$.ajax({
		type : "POST",
		url : "/bms/bookinfo/search",
		data : params,
		dataType : "json",
		contentType : "application/json; charset=UTF-8",
		success : function(data) {
			$('#book_tbody').empty();
			var bookList = data.bookList;
			totalCount = data.totalCount;
			pageCount = Math.ceil(totalCount / pageSize);
			//create table body
			createTBody(bookList, totalCount);
			
			if (pageNow == 1) {
				$('#first').attr("disabled", true);
				$('#pre').attr("disabled", true);
			} else {
				$('#first').attr("disabled", false);
				$('#pre').attr("disabled", false);
			}
			
			if (pageNow == pageCount) {
				$('#next').attr("disabled", true);
				$('#last').attr("disabled", true);
			} else {
				$('#next').attr("disabled", false);
				$('#last').attr("disabled", false);
			}
			
			if (pageNow > pageCount) {
				pageNow = 1;
				search();
			}
			
			if (pageCount == 0) {
				$("#page").html("0/0");
			} else {
				$("#page").html(pageNow + "/" + pageCount);
			}
		}
	});
}

function createTBody(list, count) {
	var tbody = '';
	var tr = '<tr>';
	var etr = '</tr>';
	var td = '<td>';
	var etd = '</td>';
	
	if (count == 0) {
		tbody += tr + '<td colspan="14"><font color="red">No relevant books!!!</font>' + etd + etr;
	} else {
		$.each(list, function(bookIndex, book) {
			bookIndex++;
			var no = td + bookIndex + etd;
			var name = td + book.name + etd;
			var bookType = td + book.bookType.name + etd;
			var author = td + book.author + etd;
			var publisher = td + book.publisher + etd;
			var price = td + book.price + etd;
			var storeTime = td + book.storeTime + etd;
			var city = td + book.city + etd;
			var totalQuantity = td + book.totalQuantity + etd;
			var comment = td + book.comment + etd;
			
			tbody += tr + no + name + bookType + author + publisher + price + storeTime + city + totalQuantity + comment + etr;
		});
	}
	
	$('#book_tbody').html(tbody);
}

function firstPage() {
	pageNow = 1;
	search();
}

function prePage() {
	pageNow--;
	search();
}

function nextPage() {
	pageNow++;
	search();
}

function lastPage() {
	pageCount = Math.ceil(totalCount / pageSize);
	pageNow = pageCount;
	search();
}
